package com.businessportal.web.filters;

import com.businessportal.web.common.AuthHelper;
import com.businessportal.web.dataaccess.entities.Login;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * Created by Vadim on 9/16/14.
 */
@WebFilter(urlPatterns ="/securepages/*")
public class AthenticateFilter implements Filter {
    public void destroy() {
    }

    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws ServletException, IOException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;

        HttpSession session = req.getSession(false);
        String uri = req.getRequestURI();
        Cookie[] cookies = req.getCookies();

        boolean isLoggedIn = false;

        if(session != null && cookies != null)
        {
            for(Cookie cookie: cookies)
            {
                if(cookie.getName().equals("user"))
                {
                    Login sessionUserAttr = (Login)session.getAttribute("user");

                    if(null == sessionUserAttr)
                        break;

                    try {
                        isLoggedIn = AuthHelper.checkIfCookieValid(sessionUserAttr.getLogin(), cookie.getValue());
                    } catch (Exception e) {
                        isLoggedIn = false;
                    }
                    break;
                }

            }

        }
        if(!isLoggedIn && !(
                uri.endsWith("/securepages/authorization.jsp") ||
                uri.endsWith("/securepages/register_user.jsp") ||
                uri.endsWith("/securepages/email_confirmation.jsp") ||
                uri.endsWith("/securepages/upload.do") ||
                uri.endsWith("upload.do") ||
                uri.endsWith("register_user.do") ||
                uri.endsWith("email_confirmation.do") ||
                uri.endsWith("loginform.do")
                )
          )
        {
            resp.sendRedirect("/securepages/loginform.do");
        }else{
            filterChain.doFilter(servletRequest, servletResponse);
        }
    }

    public void init(FilterConfig config) throws ServletException {

    }

}
